package com.itheima.shop.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.itheima.shop.entity.Category;
import com.itheima.shop.mapper.CategoryMapper;
import com.itheima.shop.service.CategoryService;

@Service
public class CategoryServiceImpl implements CategoryService{
	
	@Autowired
	private CategoryMapper categoryMapper;
	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Override
	public List<Category> findAll() {
		/*
		 * 1.先去redis找categories
		 * 2.如果找不到，那就调用mapper找，并且设置到redis
		 */
		// TODO Auto-generated method stub
		ValueOperations<String, String>  ops = redisTemplate.opsForValue();
		String categoriesString = ops.get("categories");
		List<Category> categories  = JSON.parseArray(categoriesString, Category.class);
		if(categories==null) {
			categories = categoryMapper.findAll();
			ops.set("categories", JSON.toJSONString(categories));
		}
		return categories;
	}

}
